package com.tinem.platform.module.starter.sdk.util;

import com.auth0.jwk.Jwk;
import com.auth0.jwk.JwkException;
import com.auth0.jwk.UrlJwkProvider;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tinem.platform.module.starter.sdk.page.PlatformJwt;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className JwtUtil
 * @description TODO
 * @site
 * @company
 * @create 2021/12/1 19:26:27
 */
@Slf4j
public class JwtUtil implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    String jwkSetUri;

    JWTVerifier verifier;

    public PlatformJwt getDecodedJWT(String token){
        DecodedJWT jwt = verifier.verify(token);
        return new PlatformJwt(jwt);
    }

    /**
     * 每天更新token
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void refresh() throws JwkException, MalformedURLException {
        UrlJwkProvider urlJwkProvider = new UrlJwkProvider(new URL(jwkSetUri));
        Jwk jwk = urlJwkProvider.get(null);
        verifier = JWT.require(Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(),null)).build();
    }

    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        refresh();
    }
}
